<!--
 * @Author: Leo.wang wanglizhigs@163.com
 * @Date: 2024-05-12 10:08:15
 * @LastEditors: Leo.wang wanglizhigs@163.com
 * @LastEditTime: 2024-05-12 19:09:11
 * @FilePath: /gptfront-dev/src/components/ConversationGroup/conversation?.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <view>
    <view class="conversation">
      <view class="flex items-center">
        <view class="size-5 rounded-full bg-orange-700"></view>
        <view class="ml-2 text-xs">YOU</view>
      </view>
      <view class="mt-1 pl-7">
        <view class="flex gap-2 overflow-x-auto">
          <template v-for="(file, fIdx) in question.files">
            <StyledImage
              v-if="file.type == 1"
              :key="file.fileUrl"
              :src="file.fileUrl"
              @click="handlePreviewImage(question.files, fIdx)"
            />

            <view v-else :key="file.fileUrl" class="flex items-center gap-2">
              <uni-icons font-family="heroicons-outline" :size="22">
                {{ '\ue995' }}
              </uni-icons>
              <text>{{ file.fileName }}</text>
            </view>
          </template>
        </view>
        <view
          class="rich-text-content select-text text-base"
          v-html="md.render(question.message ?? '')"
        />
      </view>
    </view>

    <view class="conversation">
      <view class="flex items-center">
        <view class="size-5 rounded-full bg-purple-600"></view>
        <view class="ml-2 text-xs">CHATGPT</view>
      </view>
      <view class="mt-1 pl-7">
        <view class="flex gap-2 overflow-x-auto">
          <template v-for="(file, fIdx) in question.files">
            <StyledImage
              v-if="file.type == 1 "
              :key="file.fileUrl"
              :src="file.fileUrl"
              @click="handlePreviewImage(question.files, fIdx)"
            />

            <view v-else :key="file.fileUrl" class="flex items-center gap-2">
              <uni-icons font-family="heroicons-outline" :size="22">
                {{ '\ue995' }}
              </uni-icons>
              <text>{{ file.fileName }}</text>
            </view>
          </template>
        </view>

        <view v-if="isGen()">
          <view v-if="isGeneratingImage" class="text-sm text-zinc-500">
            {{ t('imageGenerating') }}
          </view>
          <view
            v-else
            class="break-word"
            v-html="md.render(`${generatingMessage}●`)"
          ></view>
        </view>

        <view v-else>
          <view
            class="rich-text-content select-text text-base"
            v-html="md.render(conversation?.message ?? '')"
          />
        </view>

        <view class="mt-2 flex items-center gap-2">
          <view v-if="max > 1" class="flex items-center">
            <uni-icons
              type="left"
              size="16"
              class="pointer"
              @click="handlePrev()"
            ></uni-icons>
            <view>{{ current + 1 }}/{{ max }}</view>
            <uni-icons
              type="right"
              size="16"
              class="pointer"
              @click="handleNext()"
            ></uni-icons>
          </view>
          <uni-icons
            v-if="conversation?.files?.filter((f) => f.type === 0)?.length > 0"
            type="download"
            size="22"
            class="pointer"
            @click="download(conversation?.files)"
          ></uni-icons>
          <uni-icons
            v-if="isLast"
            type="loop"
            size="22"
            class="pointer"
            @click="handleRefresh()"
          ></uni-icons>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts">
import { computed, defineComponent, ref } from 'vue'
import { md } from '@/utils/markdown'
import StyledImage from '../StyledImage.vue'

import { useStore } from 'vuex'
import { preview } from '@/components/PreviewImage/index'
import useLocale from '@/composables/useLocale'

export default defineComponent({
  name: 'Conversation',
  components: {
    StyledImage,
  },
  props: {
    isLast: Boolean,
    question: {
      type: Object,
      default: undefined,
    },
    conversations: {
      type: Object,
      default: undefined,
    },
  },
  setup(props, { emit }) {
    const { t } = useLocale()
    const current = ref(0)

    const max = ref(
      props.conversations.length > 1 ? props.conversations.length : 1,
    )

    const conversation = computed(() => props.conversations[current.value])

    function handlePrev() {
      const result = current.value - 1
      if (result >= 0) {
        current.value = result
      }
    }
    function handleNext() {
      const result = current.value + 1
      if (result < props.conversations.length) {
        current.value = result
      }
    }

    const store = useStore()

    function handleRefresh() {
      if (props.isLast) {
        max.value = max.value + 1
        current.value = max.value - 1
      }

      store.commit('chat/setRefreshConversation', props.question.message)

      emit('sendMessage', {
        msg: props.question.message,
        files: props.question.files.map(({ url, type, fileName }) => ({
          fileUrl: url,
          type: type,
          fileName: fileName,
        })),
      })
    }

    function handlePreviewImage(files, current) {
      // const urls = files.map((file) => file.fileUrl)
      // preview.show({
      //   urls,
      // })

      const urls = files.map((file) => file.fileUrl)
      uni.previewImage({
        urls,
        current,
      })

      // uni.previewImage({
      //   urls,
      //   current,
      //   longPressActions: {
      //       itemList: ['发送给朋友', '保存图片', '收藏'],
      //       success: function(data) {
      //         console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
      //       },
      //       fail: function(err) {
      //         console.log(err.errMsg);
      //       }
      //     }
      // })
    }
    const isGenerating = computed(() => store.state.chat.isGenerating)
    const generatingMessage = computed(() => store.state.chat.generatingMessage)
    const isGeneratingImage = computed(() => store.state.chat.isGeneratingImage)
    const currentConver = computed(() => store.state.chat.refreshConversation)
    const isGen = () => {
      if (currentConver.value) {
        if (props.isLast) {
          return (
            (isGenerating.value || isGeneratingImage.value) &&
            currentConver.value === props.question.message
          )
        } else {
          return false
        }
      } else {
        return (isGenerating.value || isGeneratingImage.value) && props.isLast
      }
    }

    function download(files) {
      const urls = files.map((file) => file.fileUrl)

      urls.forEach((url) => {
        // #ifdef MP-WEIXIN
        uni.downloadFile({
          url,
          success: (response) => {
            if (response.statusCode === 200) {
              const tempFilePath = response.data.tempFilePath

              uni.saveImageToPhotosAlbum({
                filePath: tempFilePath,
              })
            }
          },
        })
        // #endif

        // #ifdef WEB

        const fileName = `${new Date()}.png`
        const xhr = new XMLHttpRequest()
        xhr.open('GET', url, true)
        xhr.responseType = 'blob'

        xhr.onload = function () {
          if (xhr.status === 200) {
            const blob = xhr.response
            const link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
        }
        xhr.send()
        // #endif
      })
    }

    return {
      conversation,
      handlePrev,
      handleNext,
      max,
      current,
      md,
      handleRefresh,
      handlePreviewImage,
      isGenerating,
      generatingMessage,
      isGeneratingImage,
      currentConver,
      isGen,
      download,
      t,
    }
  },
})
</script>

<style lang="scss" scoped>
.rich-text-content {
  p {
    line-height: 1.75rem;
  }
}

.conversation {
  & + .conversation {
    margin-top: 16px;
  }
}

.pointer {
  cursor: pointer;
}
</style>
